package com.chat.demo.auth.aspect;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.chat.demo.auth.JwtUtils;

import java.util.Objects;

@Aspect
@Component
public class JwtAuthAspect {

    private final JwtUtils jwtUtils;

    // 通过构造函数注入 JwtUtils Bean
    public JwtAuthAspect(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Around("@annotation(com.chat.demo.auth.annotation.JwtAuth) " +
            "|| @within(com.chat.demo.auth.annotation.JwtAuth)")
    public Object checkJwt(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("JwtAuthAspect: 检查 JWT Token");

        HttpServletRequest request = ((ServletRequestAttributes)
                Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                .getRequest();

        // 校验Header格式
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new RuntimeException("未提供 JWT Token");
        }

        token = token.substring(7);

        if (!jwtUtils.validateToken(token)) {
            throw new RuntimeException("无效的 JWT Token");
        }

        String username = jwtUtils.getUsernameFromToken(token);
        request.setAttribute("currentUser", username);

        return joinPoint.proceed();
    }
}